import Cookies from "js-cookie";

let isAuth: boolean | string | null;

const ajax = (url: string) => {
	return new Promise((resolve, reject) => {
		const xhr = new XMLHttpRequest();
		xhr.open("GET", url);
		xhr.setRequestHeader("Accept", "application/json");
		xhr.send();
		xhr.onreadystatechange = () => {
			if (xhr.readyState !== 4) {
				return;
			}
			const { status, statusText } = xhr;
			if (status >= 200 && status < 300) {
				// 准备结果数据对象response
				const response = {
					data: JSON.parse(xhr.response),
					status,
					statusText
				};
				// 2.1如果请求成功了，调用resolve()
				resolve(response);
			} else {
				// 2.2如果请求失败，调用reject()
				reject(new Error("request error status is " + status));
			}
		};
	});
};

export const login = (value: string, days: number = 30, auth: boolean): any => {
	/**
	 * 检查是否具备权限
	 */
	if (isAuth === null) {
		/**
		 * 刷新还未授权
		 */
		isAuth = auth;
		if (auth) {
			Cookies.set("zm-iam-token", value, { expires: days });
			sessionStorage.setItem("zm-iam-token", value);
		} else {
			sessionStorage.removeItem("zm-iam-token");
		}
	} else {
		//检查是否变更角色
		if (
			sessionStorage.getItem("zm-iam-token") &&
			Cookies.get("zm-iam-token") &&
			Cookies.get("zm-iam-token") !== sessionStorage.getItem("zm-iam-token")
		) {
			isAuth = null;
			return 10501;
		}
		if (isAuth) {
			return 0;
		} else {
			return 10400;
		}
	}
};

/**
 *
 * @returns 检查iam登录成功
 */
export const isLogined = (): boolean => {
	if (
		Cookies.get("zm-iam-token") &&
		window.sessionStorage.getItem("zm-iam-token") &&
		Cookies.get("zm-iam-token") == window.sessionStorage.getItem("zm-iam-token") &&
		isAuth
	) {
		return true;
	} else {
		return false;
	}
};

/**
 * @description 直接退出登录
 */
export const logout = (fn?: () => void): void => {
	if (isAuth) {
		//* 恢复初始状态
		Cookies.remove("zm-iam-token");
		sessionStorage.removeItem("zm-iam-token");
		isAuth = null;
		fn && fn();
	} else {
		sessionStorage.removeItem("zm-iam-token");
		isAuth = null;
		fn && fn();
	}
};
